﻿using System;
using System.Net;
using System.Web;

namespace NopSolutions.NopCommerce.BusinessLogic.HttpModules
{
    public class RedirectWwwHttpModules : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose() {
        }

        public void Init(HttpApplication context) {
            context.BeginRequest += (sender, e) => OnBeginRequest(new HttpContextWrapper(((HttpApplication)sender).Context));
        }

        #endregion

        public virtual void OnBeginRequest(HttpContextBase context) {
            // if the host isn't localhost
            if (!context.Request.Url.Host.Equals("localhost")) {
                if (!context.Request.Url.Host.StartsWith("www.")) {
                    // don't forget about https
                    string redirect = context.Request.Url.Scheme + "://www." + context.Request.Url.Authority;

                    for (int i = 0; i < context.Request.Url.Segments.Length; i++) {
                        // skip default and redirect
                        if (!context.Request.Url.Segments[i].ToLower().Equals("default.aspx"))
                            redirect += context.Request.Url.Segments[i];
                    }
                    context.Response.RedirectPermanent(redirect, true);
                }
            }
        }
    }
}
